/**
 * @brief FreeRTOS应用示例
 * @details
 * @author 王炸物联网https://blog.csdn.net/wangyx1234?spm=1000.2115.3001.5343
 * @date 2022
 * @version 1.0
 * @copyright 版权所有，禁止用于商业用途
 */
#include <stdio.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_log.h"

#include "button.h"

TaskHandle_t task1; // 任务1结构对象

static int task1_flag;           // 用于指示任务运行状态的标志变量    

static int button_start_stop_callback(void * para1, void * para2)
{
    for (int i = 3; i >= 0; i--) {
        printf("Restarting in %d seconds...\n", i);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
    printf("Restarting now.\n");
    fflush(stdout);
    esp_restart();
}

static int button1_callback(void * para1, void * para2)
{
    printf("button1 pressed.\n");
    return 0;
}

/**
 * 任务的运行代码
 * @param param 任务初始运行参数
 */
static void task1_process(void *arg)
{
    static const char *TASK1_TAG = "TASK1";
    while (1) {
        ESP_LOGI(TASK1_TAG, "task1_flag = %d, arg1 = %s", task1_flag, (char *)arg);
        task1_flag++;
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

static void init(void) {
    printf("Hello world!\n");

    /* Print chip information */
    esp_chip_info_t chip_info;
    esp_chip_info(&chip_info);
    printf("This is %s chip with %d CPU core(s), WiFi%s%s, ",
            CONFIG_IDF_TARGET,
            chip_info.cores,
            (chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "",
            (chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : "");

    printf("Minimum free heap size: %d bytes\n", esp_get_minimum_free_heap_size());
}

void app_main(void)
{
    init();
    iot_button_t button1_config = {
        .button_gpio_num = 23,
        .priority = button_priority_low,
        .button_cb = button1_callback,
    };

    iot_button_t restart_button_config = {
        .button_gpio_num = 22,
        .priority = button_priority_high,
        .button_cb = button_start_stop_callback,
    };

    button_handle_t button1 = button_create(button1_config);
    
    button_handle_t restart_button = button_create(restart_button_config);
    
    printf_register_button_gpio_num();
    vTaskDelay(10000 / portTICK_PERIOD_MS);
    button_delete(button1);
    printf("button1 delete\r\n");
    /*
    static BaseType_t xTaskCreate(TaskFunction_t pvTaskCode, const char *constpcName, const uint32_t usStackDepth, 
    void *constpvParameters, UBaseType_t uxPriority, TaskHandle_t *constpxCreatedTask)*/
    // xTaskCreate(&task1_process, "task1", 1024*2, (void *)"1", configMAX_PRIORITIES, &task1); // configMAX_PRIORITIES = 25
}
